package com.sdx.console.answer.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.question.entity.QaQuestion;
import com.sdx.console.question.service.QaQuestionService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.mockito.internal.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.answer.entity.*;
import com.sdx.console.answer.service.*;
import com.sdx.console.answer.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * answer 接口
 */
@RequestMapping("/answer/answer")
@Controller
public class QaAnswerController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(QaAnswerController.class);
    private static final String MODEL = "/answer/answer";

    @Resource
	private QaAnswerService answerService;
    @Resource
    private QaQuestionService questionService;
    @Resource
    private CustomerInfoService customerInfoService;
    @Resource
    private ResCloudFileService resCloudFileService;
    @Resource
    private BaseDataService baseDataService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        String qusetionId = request.getParameter("questionId");
	    if(StringUtils.isNotEmpty(qusetionId)){
            view.addObject("questionId",qusetionId);
            view.addObject("questionTitle",questionService.queryById(qusetionId).getTitle());
        }else {
            view.addObject("questionId","");
            view.addObject("questionTitle","");
        }
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setIsTeacher(1);
        List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
        view.addObject("customerInfoList",customerInfoList);
        view.addObject("provinceList",baseDataService.getAllProvince());
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("answer.answer.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("answer.answer.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Long answerId) {

        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        QaAnswer answer = answerService.queryById(answerId);

        QaQuestion qaQuestion = questionService.queryById(answer.getQuestionId());
        if(qaQuestion!=null) {
            answer.setQuestionTitle(qaQuestion.getTitle());
        }
        view.addObject("answer", answer);
		setPageParam(view,request);

		try {
			view.addObject("answerJson", JacksonUtils.toJsonString(answer,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("answer.answer.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("answer.answer.query")
    @ResponseBody
    public JsonResult<PageQuery> list(QaAnswer condtion)
    {
        PageQuery page = condtion.getPageQuery();
        answerService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,QaAnswer answer,HttpServletRequest request) {

    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);
		log.info("answer.CustomerId"+answer.getCustomerId());
    	if (isNew) {
			answer.setCreateTime(new Date());
			answerService.save(answer);
			//更新回答数
            QaQuestion qaQuestion = questionService.queryById(answer.getQuestionId());
            if(StringUtils.isNotEmpty(qaQuestion.getAnswerCount())) {
                try{
                    int answerCount = Integer.valueOf(qaQuestion.getAnswerCount());
                    answerCount = answerCount+1;
                    qaQuestion.setAnswerCount(String.valueOf(answerCount));
                    questionService.update(qaQuestion);
                }catch (Exception ex){ex.printStackTrace();}
            }
		} else {
			answerService.updateTemplate(answer);
		}
		return result;
	}

    @PostMapping("/add.json")
    @Function("answer.answer.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)QaAnswer answer,HttpServletRequest request)
    {
        return save(true,answer,request);
    }

    @PostMapping("/update.json")
    @Function("answer.answer.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  QaAnswer answer,HttpServletRequest request) {
		return save(false,answer,request);
    }

    @GetMapping("/view.json")
    @Function("answer.answer.query")
    @ResponseBody
    public JsonResult<QaAnswer>queryInfo(Long answerId) {
        QaAnswer answer = answerService.queryById( answerId);
        return  JsonResult.success(answer);
    }

    @PostMapping("/delete.json")
    @Function("answer.answer.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        //更新回答数
        QaAnswer answer = answerService.queryById(idList.get(0));
        QaQuestion qaQuestion = questionService.queryById(answer.getQuestionId());
        if(StringUtils.isNotEmpty(qaQuestion.getAnswerCount())) {
            try{
                int answerCount = Integer.valueOf(qaQuestion.getAnswerCount());
                answerCount = answerCount-idList.size();
                qaQuestion.setAnswerCount(String.valueOf(answerCount));
                questionService.update(qaQuestion);
            }catch (Exception ex){ex.printStackTrace();}
        }
        answerService.batchDelQaAnswer(idList);
        answerService.batchDelQaAnswerCommentByIds(idList);

        return JsonResult.success();
    }

    /**
     *  图片上传
     * @param file
     * @return
     */
    @RequestMapping("/upload.json")
    @ResponseBody
    public JSONObject uploadImg(MultipartFile file) {
        JSONObject jsobject = new JSONObject();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/answer/"+dir+"/";
        String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(file)) {
            try
            {
                String fileNamePair = FileUtils.upload(subPath,file);
                String storeFile = fileNamePair.split("::")[0];
                storeFile = subPath+storeFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
                String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
                jsobject.put("url",url);
                jsobject.put("state", "SUCCESS");
                jsobject.put("title", "");
                jsobject.put("original", "");
                resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","学校logo");
            }catch(Exception e) {
                e.printStackTrace();
                jsobject.put("state", "FAIL");
                jsobject.put("title", "");
                jsobject.put("original", "");
                jsobject.put("url","");
            }
        }
        return jsobject;
    }
}
